package com.smartstate.EnvironmentMonitor.mqtt.callback;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smartstate.EnvironmentMonitor.mqtt.client.MyMQTTClient;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class MyMQTTCallback implements MqttCallback {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyMQTTCallback.class);

    private MyMQTTClient myMQTTClient;


    private static final ThreadPoolExecutor threadpool = new ThreadPoolExecutor(100, 200,
            10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    public MyMQTTCallback(MyMQTTClient myMQTTClient) {
        this.myMQTTClient = myMQTTClient;
    }

    /**
     * 丢失连接，可在这里做重连
     * 只会调用一次
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
    }

    /**
     * @param topic
     * @param message
     * @throws Exception subscribe后得到的消息会执行到这里面
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {

    }

    /**
     * Json格式转译
     *
     * @param jsonObj
     * @return
     */
    public Map<String, Object> analysis(JSONObject jsonObj) {
        JSONArray readResults = jsonObj.getJSONArray("values");
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < readResults.size(); i++) {
            JSONObject jsonObject = readResults.getJSONObject(i);
            String[] split = jsonObject.getString("id").split("\\.");
            String id = split[split.length - 1];
            Object value = 0;
            if (Boolean.parseBoolean(jsonObject.get("q").toString())) {
                value = jsonObject.get("v");
            }
            map.put(id, value);
        }
        return map;
    }

    /**
     * 消息到达后
     * subscribe后，执行的回调函数
     *
     * @param s
     * @param mqttMessage
     * @throws Exception
     */

    /**
     * publish后，配送完成后回调的方法
     *
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        LOGGER.info("==========deliveryComplete={}==========", iMqttDeliveryToken.isComplete());
    }
}
